package com.hqd.ch03.v50.boot.context.config;

import com.hqd.ch03.v50.boot.origin.Origin;
import com.hqd.ch03.v50.boot.origin.OriginTrackedResource;
import com.hqd.ch03.v50.core.env.PropertySource;
import com.hqd.ch03.v50.io.Resource;

import java.io.IOException;
import java.util.List;

public class StandardConfigDataLoader implements ConfigDataLoader<StandardConfigDataResource> {

    private static final ConfigData.PropertySourceOptions PROFILE_SPECIFIC =
            ConfigData.PropertySourceOptions.always(ConfigData.Option.PROFILE_SPECIFIC);

    private static final ConfigData.PropertySourceOptions NON_PROFILE_SPECIFIC =
            ConfigData.PropertySourceOptions.ALWAYS_NONE;

    @Override
    public ConfigData load(ConfigDataLoaderContext context, StandardConfigDataResource resource)
            throws IOException, ConfigDataNotFoundException {
        /**
         * 空文件夹
         */
        if (resource.isEmptyDirectory()) {
            return ConfigData.EMPTY;
        }
        /**
         * 判断文件是否存在
         */
        ConfigDataResourceNotFoundException.throwIfDoesNotExist(resource, resource.getResource());
        /**
         * 获取资源信息
         */
        StandardConfigDataReference reference = resource.getReference();

        Resource originTrackedResource = OriginTrackedResource.of(resource.getResource(),
                Origin.from(reference.getConfigDataLocation()));
        String name = String.format("Config resource '%s' via location '%s'", resource,
                reference.getConfigDataLocation());
        /**
         * 调用具体加载器进行加载
         */
        List<PropertySource<?>> propertySources = reference.getPropertySourceLoader()
                .load(name, originTrackedResource);
        ConfigData.PropertySourceOptions options = (resource.getProfile() != null) ? PROFILE_SPECIFIC : NON_PROFILE_SPECIFIC;
        return new ConfigData(propertySources, options);
    }
}
